package middleware

import (
	"fmt"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/glog"
	"net/http"
)

// MiddlewareHandlerResponse is the default middleware handling handler response object and its error.
func AdminMiddlewareHandlerResponse(r *ghttp.Request) {
	r.Middleware.Next()

	// There's custom buffer content, it then exits current handler.
	if r.Response.BufferLength() > 0 {
		return
	}

	var (
		msg  string
		ctx  = r.Context()
		err  = r.GetError()
		res  = r.GetHandlerResponse()
		code = gerror.Code(err)
		Error string
	)
	if err != nil {
		g.Dump("中间件发现报错了,错误原因如下",err.Error())
		if code == gcode.CodeNil {
			code = gcode.CodeInternalError
		}
		Error = err.Error()
	} else if r.Response.Status > 0 && r.Response.Status != http.StatusOK {
		msg = http.StatusText(r.Response.Status)
		switch r.Response.Status {
		case http.StatusNotFound:
			code = gcode.CodeNotFound
		case http.StatusForbidden:
			code = gcode.CodeNotAuthorized
		default:
			code = gcode.CodeUnknown
		}
		Error = fmt.Sprintf("HTTP状态码:%v 对应HTTP错误原因是: %v", code, msg)
	} else {
		code = gcode.CodeOK
		Error = ""
	}
	var internalErr error
	internalErr = r.Response.WriteJson(AdminHandlerResponse{
			Status: 1,
			Error:  Error,
			Data:   res,
	})
	if internalErr != nil {
		glog.Errorf(ctx, `%+v`, internalErr)
	}

}
